"""
Author: Morphlng
Date: 2024-12-14 20:47:33
LastEditTime: 2024-12-14 21:15:41
LastEditors: Morphlng
Description: 
FilePath: /DrivingGym/src/driving_gym/environment/agent/done/done_handler.py
"""

from __future__ import annotations

import os
from typing import TYPE_CHECKING

from driving_gym.data.data_provider import Snapshot
from driving_gym.environment.agent.done.base_done import BaseDone
from driving_gym.environment.scenario.base_scenario import BaseScenario
from driving_gym.misc.util import dynamic_import

if TYPE_CHECKING:
    from driving_gym.simulation.adapter_interface import AdapterInterface


class DoneHandler:
    def __init__(self, config: dict, adapter: "AdapterInterface"):
        self.config = config.copy()
        self._handler = self._create_handler(self.config, adapter)

    def reset(self):
        self._handler.reset()

    def _create_handler(self, config: dict, adapter: "AdapterInterface") -> BaseDone:
        done_type = config["type"]
        root = os.path.join(os.path.dirname(__file__))
        handler = dynamic_import(
            done_type,
            root,
            args=(config, adapter),
            suffix="_done",
        )
        return handler

    def get_done(self, snapshot: Snapshot, scenario: BaseScenario) -> tuple[bool, str]:
        """Check if any done condition is met.

        Args:
            snapshot (Snapshot): The snapshot containing all data of the current frame.

        Returns:
            done (float): Whether its done.
            details (str): Cause of done.
        """
        return self._handler.get_done(snapshot, scenario)
